#include <xscript/xscriptexecutor.h>
#include <astree/xabstractasyntaxtreevariable.h>
#include <astree/xabstractsyntaxtreeparser.h>
#include <astree/xabstractsyntaxtreevalue.h>
#include <astree/xabstractsyntaxtreearithmetic.h>

bool XAbstractSyntaxTreeParserValue::isCurrentHighPrority(const std::wstring& top, const std::wstring& current) {
    if ((top == L"+" || top == L"-") && (current == L"*" || current == L"/"))
        return true;
    return false;
}

XAbstractSyntaxTreePtr XAbstractSyntaxTreeParserValue::parse(const std::vector<XTokenPtr>& tokens) {
    for (size_t i = 0; i < tokens.size(); i++) {
        auto token = tokens.at(i);
        if (token->asBoolean() || token->asFloat() || token->asInteger() || token->asString() || token->asVariable()) {
            auto tag = token->getString();
            auto node = std::make_shared<XAbstractSyntaxTreeValue>(token);
            if (stack.empty()) {
                stack.push(node);
                prev = node;
            } else {
                prev->addChild(node);
                prev = node;
            }
        } else if (token->asPunctuator()) {
            auto tag = token->getString();
            if (stack.empty()) {
                XScriptExecutor::getInstance()->setError(XError::XError_BadTokenError, token->toString());
                return nullptr;
            }

            if (tag != L"+" && tag != L"-" && tag != L"*" && tag != L"/") {
                XScriptExecutor::getInstance()->setError(XError::XError_BadTokenError, token->toString());
                return nullptr;
            }

            auto current = XAbstractSyntaxTree::createFromToken(token);
            auto top = stack.top();
            stack.pop();

            current->addChild(top);
            stack.push(current);

            prev = current;
        }
    }

    assert(stack.size() == 1);
    return stack.top();
}
